const router = require('express').Router()
const {createToken} = require('../utils/jwt')
const md5 = require('md5')
const {query} = require('../db')

// 前端登录操作
// /api/login
router.post('/login', async (req, res) => {
  // 业务判断
  let {username, password} = req.body
  password = md5(password)
  // 1.查询对应用户是否存在
  var sql = `select id,username,nickname,role from users where username='${username}' and password='${password}'`
  const userData = await query(sql)
  if (userData.length == 0) {
    return res.send({
      code: 1,
      msg: '账号或密码不正确',
      data: {}
    })
  }
  // 2.查询得到当前的角色对应的权限
  var sql = `select id,auths from roles where id=${userData[0].role}`
  const rolesData = await query(sql)
  if (rolesData.length == 0) {
    return res.send({
      code: 1,
      msg: '账号或密码不正确',
      data: {}
    })
  }

  // 3.查询权限节点
  var sql = `select * from auths where id in (${rolesData[0].auths})`
  const authsData = await query(sql)
  if (authsData.length == 0) {
    return res.send({
      code: 1,
      msg: '账号或密码不正确',
      data: {}
    })
  }

  // 4.登录成功，生成token让它保持状态
  const token = createToken({
    uid: userData[0].id,
    username,
    exp: Date.now() + 7200000
  })

  return res.send({
    code: 0,
    msg: '登录成功',
    data: {
      uid: userData[0].id,
      role: rolesData[0].id,
      nickname: userData[0].nickname,
      // 菜单数据 -- 权限数据
      nodes: authsData,
      token,
    }
  })
})


module.exports = router
